#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import os
import shutil

from openpyxl import load_workbook


class XlsxFile:
    """docstring for XlsxFile"""

    def __init__(self, sourcefiles, cols, targets, start_row, index=None):
        self.sourcefiles = sourcefiles
        self.cols = cols
        self.targets = targets

        self.start_row = start_row
        self.index = index

        self.target_dir = "结果"

        print("config", sourcefiles, cols, targets, start_row)

    def read_from_xlsx(self, path, row_offset=0, max_col=0):
        """从 xlsx 文件读取数据，0索引"""
        print("rec", path, row_offset)
        wb = load_workbook(path, data_only=True)
        ws = wb.active
        data = list(ws.values)[row_offset:]
        res = []
        for row in data:
            sub_row = row if max_col == 0 else row[:max_col]
            res.append(sub_row)
        return res

    def fill_data(self, ws, current_row, data):
        print("fd", range(len(data)), range(ws.max_column))
        i = 0
        for r in range(len(data)):
            for c in range(ws.max_column):
                ws.cell(current_row + i, c + 1).value = data[r][c]
            i += 1

        return current_row + i

    def check_dir(self):
        if os.path.exists(self.target_dir):
            shutil.rmtree(self.target_dir)
        os.mkdir(self.target_dir)

    def del_ws_rows(self, ws, to_del_rows):
        to_del_rows.reverse()
        for r in to_del_rows:
            ws.delete_rows(r, 1)

    def check(self, line, items):
        result = True
        for i in range(len(self.cols)):
            if str(line[self.cols[i]].value) != items[i]:
                result = False
                break
        return result

    def split(self):
        self.check_dir()
        from_wb = load_workbook(self.sourcefiles[0])

        for items in self.targets:
            name = "-".join(items)
            one_file = f"{self.target_dir}/{name}.xlsx"
            from_wb.save(one_file)

            new_wb = load_workbook(one_file)
            new_ws = new_wb.active
            not_current_classes = []
            i = self.start_row
            for r in new_ws.iter_rows(min_row=self.start_row):

                if not self.check(r, items):
                    not_current_classes.append(i)

                i += 1
            self.del_ws_rows(new_ws, not_current_classes)
            if self.index != None:
                j = 1
                for r in new_ws.iter_rows(min_row=self.start_row):
                    r[self.index].value = j
                    j += 1

            new_wb.save(one_file)

        print("完成")

    def merge(self):

        dst_file = f"结果/合并-{os.path.basename(self.sourcefiles[0])}"
        print("dst file", dst_file, self.start_row, type(self.sourcefiles[0]))
        target_wb = load_workbook(self.sourcefiles[0])
        target_wb.save(dst_file)

        target_wb = load_workbook(dst_file)
        target_ws = target_wb.active

        current_row = self.start_row
        for sourcefile in self.sourcefiles:
            print("处理", type(sourcefile))
            incoming_data = self.read_from_xlsx(sourcefile, self.start_row - 1)
            print(f"数据行数：{len(incoming_data)}")
            current_row = self.fill_data(
                target_ws, current_row=current_row, data=incoming_data
            )

            print("fill to row", current_row)
        target_wb.save(dst_file)

        print("完成", dst_file)
